package cn.yxvk.spring.security.oauth2.server.config;

import cn.yxvk.spring.security.oauth2.server.domain.TbPermission;
import cn.yxvk.spring.security.oauth2.server.domain.TbUser;
import cn.yxvk.spring.security.oauth2.server.service.TbPermissionService;
import cn.yxvk.spring.security.oauth2.server.service.TbUserService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author yangxiang
 * @date 2019/10/31 9:43
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private TbUserService tbUserService;

    @Autowired
    private TbPermissionService tbPermissionService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TbUser tbUser=tbUserService.getByUserName(s);
        List<GrantedAuthority> grantedAuthorities= Lists.newArrayList();
        if (tbUser!=null){
            List<TbPermission> tbPermissions=tbPermissionService.selectByUserId(tbUser.getId());
            tbPermissions.forEach(tbPermission ->  {
                //放行权限名配置，路径
                grantedAuthorities.add(new SimpleGrantedAuthority(tbPermission.getName()));
            });
            return new User(tbUser.getUsername(),tbUser.getPassword(),grantedAuthorities);
        }
        return null;
    }
}
